package com.shushan.lockscreen;

import android.Manifest;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.permission.PermissionRequestUtil;
import com.shushan.base.ActivityStackManager;
import com.shushan.base.BaseActivity;
import com.shushan.base.Constants;
import com.shushan.service.DialRTAService;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.HomeSwitchActivity;
import com.shushan.shushanbao.R;
import com.shushan.ui.FloatToast;
import com.shushan.util.ControlUtil;
import com.shushan.util.DateUtils;
import com.shushan.util.SharedPreferencesUtils;
import com.shushan.util.SystemUtils;
import com.shushan.util.ToastUtils;

import java.util.Timer;
import java.util.TimerTask;

/**
 * @ClassName: PinLockFloatWindow
 * @Desciption: 密码锁屏浮窗
 * @author: yichaohua
 * @date: 2017-12-21
 */
public class PinLockFloatWindow extends LinearLayout implements TextWatcher, View.OnClickListener {

    private static final String TAG = "PinLockFloatWindow";

    private static final int PASSWORD_TEXT_MAX_LENGTH = 16;
    private static final int PASSWORD_TEXT_LENGTH = 6;

    private Context mContext;
    private BabyApplication ssApplication = BabyApplication.getInstance();

    private TextView pwdEdit;
    private LinearLayout layout0,layout1,layout2,layout3,layout4,layout5,
            layout6,layout7,layout8,layout9,urgentLayout,deleteLayout;
    private TextView timeTextView,dateTextView,weekTextView,forgetTextView;
    private LinearLayout dialogLayout;
    private RelativeLayout cancelLayout,okLayout;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0:
                    weekTextView.setText(DateUtils.getNowWeek());
                    dateTextView.setText(DateUtils.getNowDate("MM月dd日"));
                    timeTextView.setText(DateUtils.getNowDate("HH:mm"));
                    break;
                default:
                    break;
            }
        }
    };

    public PinLockFloatWindow(Context context) {
        super(context);

        Log.i(TAG,"PinLockFloatWindow()");

        LayoutInflater.from(context).inflate(R.layout.pin_lock_screen_activity, this);

        this.mContext = context;

        initView();

        Timer timer = new Timer();
        timer.schedule(new DateTimerTask(),0,1000*30);
    }

    private void initView() {
        cancelLayout = findViewById(R.id.dialog_cancel_layout);
        cancelLayout.setOnClickListener(this);
        okLayout = findViewById(R.id.dialog_ok_layout);
        okLayout.setOnClickListener(this);
        dialogLayout = findViewById(R.id.dialog_show_layout);
        forgetTextView = findViewById(R.id.pin_lock_screen_forget_textview);
        forgetTextView.setOnClickListener(this);
        weekTextView = findViewById(R.id.pin_lock_screen_week_textview);
        weekTextView.setText(DateUtils.getNowWeek());
        dateTextView = findViewById(R.id.pin_lock_screen_date_textview);
        dateTextView.setText(DateUtils.getNowDate("MM月dd日"));
        timeTextView = findViewById(R.id.pin_lock_screen_time_textview);
        timeTextView.setText(DateUtils.getNowDate("HH:mm"));
        pwdEdit = findViewById(R.id.pin_lock_screen_pwd_edit);
        pwdEdit.addTextChangedListener(this);
        layout0 = findViewById(R.id.pin_lock_screen_0_layout);
        layout0.setOnClickListener(this);
        layout1 = findViewById(R.id.pin_lock_screen_1_layout);
        layout1.setOnClickListener(this);
        layout2 = findViewById(R.id.pin_lock_screen_2_layout);
        layout2.setOnClickListener(this);
        layout3 = findViewById(R.id.pin_lock_screen_3_layout);
        layout3.setOnClickListener(this);
        layout4 = findViewById(R.id.pin_lock_screen_4_layout);
        layout4.setOnClickListener(this);
        layout5 = findViewById(R.id.pin_lock_screen_5_layout);
        layout5.setOnClickListener(this);
        layout6 = findViewById(R.id.pin_lock_screen_6_layout);
        layout6.setOnClickListener(this);
        layout7 = findViewById(R.id.pin_lock_screen_7_layout);
        layout7.setOnClickListener(this);
        layout8 = findViewById(R.id.pin_lock_screen_8_layout);
        layout8.setOnClickListener(this);
        layout9 = findViewById(R.id.pin_lock_screen_9_layout);
        layout9.setOnClickListener(this);
        deleteLayout = findViewById(R.id.pin_lock_screen_delete_layout);
        deleteLayout.setOnClickListener(this);
        urgentLayout = findViewById(R.id.pin_lock_screen_urgent_layout);
        urgentLayout.setOnClickListener(this);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if(s.length() == PASSWORD_TEXT_LENGTH){
            String parentPasswd = SharedPreferencesUtils.getStringDate(
                    Constants.PARENT_PASSWD_SHAREPREFERS_KEY,"");
            String freeGamePsw = SharedPreferencesUtils.getStringDate(
                    Constants.FREE_GAME_PSW_SHAREPREFERS_KEY,"");

            if(s.toString().equals(parentPasswd)){
                unLockScreen();
            }else if(s.toString().equals(freeGamePsw)){
                ControlUtil.gotoPswGamesFloat(mContext);
                LockScreenWindowManager.removeLockFloatWindow(mContext);
            } else {
                forgetTextView.setVisibility(VISIBLE);
            }

        }else if(s.length() > PASSWORD_TEXT_LENGTH){
            clearPwd();
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.pin_lock_screen_0_layout:
                addPwdText(0);
                break;
            case R.id.pin_lock_screen_1_layout:
                addPwdText(1);
                break;
            case R.id.pin_lock_screen_2_layout:
                addPwdText(2);
                break;
            case R.id.pin_lock_screen_3_layout:
                addPwdText(3);
                break;
            case R.id.pin_lock_screen_4_layout:
                addPwdText(4);
                break;
            case R.id.pin_lock_screen_5_layout:
                addPwdText(5);
                break;
            case R.id.pin_lock_screen_6_layout:
                addPwdText(6);
                break;
            case R.id.pin_lock_screen_7_layout:
                addPwdText(7);
                break;
            case R.id.pin_lock_screen_8_layout:
                addPwdText(8);
                break;
            case R.id.pin_lock_screen_9_layout:
                addPwdText(9);
                break;
            case R.id.pin_lock_screen_delete_layout:
                addPwdText(-1);
                break;
            case R.id.pin_lock_screen_urgent_layout:
                clearPwd();
                break;
            case R.id.pin_lock_screen_forget_textview:
                boolean hasPermission = PermissionRequestUtil.judgePermission(
                        mContext,new String[]{Manifest.permission.CALL_PHONE,},100);
                Log.i(TAG,"hasPermission=" + hasPermission);
                if(hasPermission){
                    dialogLayout.setVisibility(VISIBLE);
                    setAllClickListener(null);
                }else {
                    ToastUtils.showToast(mContext,"无权限拨打电话");
                }

                break;
            case R.id.dialog_cancel_layout:
                dialogLayout.setVisibility(GONE);
                setAllClickListener(this);
                break;
            case R.id.dialog_ok_layout:
                dialCustom();
                break;
            default:
                break;
        }
    }

    private void addPwdText(int num) {
        Log.i(TAG,"addPwdText num=" + num);
        String pwd = pwdEdit.getText().toString();
        if(num >= 0 && pwd.length() > PASSWORD_TEXT_MAX_LENGTH){
            return;
        }

        if(num >= 0){
            pwdEdit.setText(pwd + num);
        }else {
            if(TextUtils.isEmpty(pwd)){
                return;
            }

            pwdEdit.setText(pwd.substring(0,pwd.length() - 1));
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
            case KeyEvent.KEYCODE_MENU:
                return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    private class DateTimerTask extends TimerTask{

        @Override
        public void run() {
            Log.i(TAG,"DateTimerTask run");
            handler.sendEmptyMessage(0);
        }
    }

    private void unLockScreen() {
        boolean isSoftOpen = SharedPreferencesUtils.getBooleanDates(Constants.GO_SOFT_SWITCH_SHAREPREFERS_KEY);
        Log.i(TAG,"isSoftOpen=" + isSoftOpen);

        if(isSoftOpen){
            SystemUtils.sendForegActivity(mContext,HomeSwitchActivity.class);
        }else {
            BaseActivity baseActivity = (BaseActivity) ActivityStackManager.getActivityStackManager().currentActivity();
            if(baseActivity != null){
                baseActivity.setAllowBack(true);
            }
            ActivityStackManager.getActivityStackManager().popAllActivity();
        }

        LockScreenWindowManager.removeLockFloatWindow(mContext);
    }

    public void clearPwd(){
        pwdEdit.setText("");
    }

    public void setForgetGone(){
        if(forgetTextView != null){
            forgetTextView.setVisibility(GONE);
        }
    }

    private void setAllClickListener(OnClickListener onClickListener) {
        forgetTextView.setOnClickListener(onClickListener);
        layout0.setOnClickListener(onClickListener);
        layout1.setOnClickListener(onClickListener);
        layout2.setOnClickListener(onClickListener);
        layout3.setOnClickListener(onClickListener);
        layout4.setOnClickListener(onClickListener);
        layout5.setOnClickListener(onClickListener);
        layout6.setOnClickListener(onClickListener);
        layout7.setOnClickListener(onClickListener);
        layout8.setOnClickListener(onClickListener);
        layout9.setOnClickListener(onClickListener);
        deleteLayout.setOnClickListener(onClickListener);
        urgentLayout.setOnClickListener(onClickListener);
    }

    private void dialCustom() {
        if(!SystemUtils.checkUsagePermission(mContext)){
            FloatToast.makeText(mContext,"请先设置“有权查看应用使用情况”权限").show();
            return;
        }
        setAllClickListener(this);
        dialogLayout.setVisibility(GONE);

        boolean isChildControl = SharedPreferencesUtils.getBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY);
        Log.i(TAG,"isChildControl=" + isChildControl);
        if(isChildControl){
            BaseActivity baseActivity = (BaseActivity) ActivityStackManager.getActivityStackManager().currentActivity();
            if(baseActivity != null){
                baseActivity.setAllowBack(true);
            }

            try {
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + Constants.CLIENT_PHONE_NUM));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(intent);
            }catch (SecurityException se){
                se.printStackTrace();
                FloatToast.makeText(mContext,"没有打电话权限").show();
                return;
            }

            Intent intent = new Intent(mContext,DialRTAService.class);
            intent.putExtra("rtaType",1);
            intent.putExtra("allowPackName",Constants.ALLOW_DIAL_PACK_NAME);
            mContext.startService(intent);

            LockScreenWindowManager.removeLockFloatWindow(mContext);
        }

    }
}
